<template>
  <div class="page">
    <div class="form-wrap">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="接口名称">
          <el-input v-model="form.apiName" />
        </el-form-item>
        <el-form-item label="请求方式">
          <el-select clearable v-model="form.apiMethod" style="width: 100%">
            <el-option value="GET"> GET </el-option>
            <el-option value="POST"> POST </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select clearable v-model="form.categoryCode" style="width: 100%">
            <el-option
              v-for="(item, index) in categoryEnumList"
              :key="index"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口描述">
          <el-input v-model="form.remark" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
    </div>
    <div class="table-top">
      请求参数
      <el-button type="primary" @click="requestFormAdd()"> 添加 </el-button>
    </div>
    <el-table
      :data="requestList"
      row-key="uuid"
      :tree-props="{ children: 'childList' }"
    >
      <el-table-column label="字段" prop="fieldName" />
      <el-table-column label="类型" prop="fieldType">
        <template slot-scope="scope">
          {{ fieldTypeMap[scope.row.fieldType] }}
        </template>
      </el-table-column>
      <el-table-column label="最大长度" prop="maxLength" />
      <el-table-column label="是否必填" prop="required">
        <template slot-scope="scope">
          {{ scope.row.required === "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="示例值" prop="exampleValue" />
      <el-table-column label="字段描述" prop="remark" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="requestFormAdd(scope.row)"
            v-if="scope.row.fieldType === 7"
          >
            添加
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="requestFormDetail(scope.row)"
          >
            编辑
          </el-button>
          <el-button size="mini" type="text" @click="requestFormDel(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
      class="table-top"
      :style="{
        marginTop: '50px',
      }"
    >
      响应参数
      <el-button type="primary" @click="responseFormAdd"> 添加 </el-button>
    </div>
    <el-table
      :data="responseList"
      row-key="uuid"
      :tree-props="{ children: 'childList' }"
    >
      <el-table-column label="字段" prop="fieldName" />
      <el-table-column label="类型" prop="fieldType">
        <template slot-scope="scope">
          {{ fieldTypeMap[scope.row.fieldType] }}
        </template>
      </el-table-column>
      <el-table-column label="最大长度" prop="maxLength" />
      <el-table-column label="是否必填" prop="required">
        <template slot-scope="scope">
          {{ scope.row.required === "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="示例值" prop="exampleValue" />
      <el-table-column label="字段描述" prop="remark" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="responseFormAdd(scope.row)"
            v-if="scope.row.fieldType === 7"
          >
            添加
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="responseFormDetail(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="responseFormDel(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-top">响应示例</div>
    <CodeEditor v-model="responseExample" />
    <div class="table-top">请求示例</div>
    <CodeEditor v-model="requestExample" />
    <div class="footer">
      <el-button type="primary" @click="handleSave"> 保存 </el-button>
      <el-button @click="$router.back()"> 返回 </el-button>
    </div>
    <!-- 请求参数 -->
    <el-dialog
      v-if="requsetVisible"
      title="请求参数"
      :visible.sync="requsetVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="requestForm" :model="requestForm" label-width="80px">
        <el-form-item label="字段" prop="fieldName">
          <el-input v-model="requestForm.fieldName" />
        </el-form-item>
        <el-form-item label="类型" prop="fieldType">
          <el-select
            clearable
            v-model="requestForm.fieldType"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in fieldTypeEnumList"
              :key="index"
              :value="item.code"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最大长度" prop="maxLength">
          <el-input v-model="requestForm.maxLength" />
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-select
            clearable
            v-model="requestForm.required"
            style="width: 100%"
          >
            <el-option value="1" label="是"></el-option>
            <el-option value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="示例值" prop="exampleValue">
          <el-input v-model="requestForm.exampleValue" />
        </el-form-item>
        <el-form-item label="字段描述" prop="remark">
          <el-input v-model="requestForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="requestFormSubmit">确 定</el-button>
        <el-button @click="requestFormCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 响应参数 -->
    <el-dialog
      v-if="responseVisible"
      title="响应参数"
      :visible.sync="responseVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="responseForm" :model="responseForm" label-width="80px">
        <el-form-item label="字段" prop="fieldName">
          <el-input v-model="responseForm.fieldName" />
        </el-form-item>
        <el-form-item label="类型" prop="fieldType">
          <el-select
            clearable
            v-model="responseForm.fieldType"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in fieldTypeEnumList"
              :key="index"
              :value="item.code"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最大长度" prop="maxLength">
          <el-input v-model="responseForm.maxLength" />
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-select
            clearable
            v-model="responseForm.required"
            style="width: 100%"
          >
            <el-option value="1" label="是"> </el-option>
            <el-option value="0" label="否"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="示例值" prop="exampleValue">
          <el-input v-model="responseForm.exampleValue" />
        </el-form-item>
        <el-form-item label="字段描述" prop="remark">
          <el-input v-model="responseForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="responseFormSubmit">确 定</el-button>
        <el-button @click="responseFormCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";
import { v4 as uuidv4 } from "uuid";
import { deepClone } from "@/utils/index.js";
import CodeEditor from "@/components/codeEditor.vue";
import { Message } from "element-ui";
export default {
  components: { CodeEditor },
  data() {
    return {
      responseExample: "",
      requestExample: "",
      form: {
        categoryCode: "",
        categoryName: "",
        apiMethod: "",
        apiName: "",
        remark: "",
      },
      categoryEnumList: [],
      fieldTypeEnumList: [],
      fieldTypeMap: {},
      requestList: [],
      requestRules: {},
      requsetVisible: false,
      requestForm: {
        fieldName: "",
        fieldType: null,
        maxLength: null,
        required: null,
        exampleValue: "",
        remark: "",
      },
      responseList: [],
      responseRules: {},
      responseVisible: false,
      responseForm: {
        fieldName: "",
        fieldType: null,
        maxLength: null,
        required: null,
        exampleValue: "",
        remark: "",
      },
    };
  },
  mounted() {
    let queryParams = this.$route.query;
    if (queryParams.id) {
      this.getInfo();
    }
    this.getApiCategoryEnum();
    this.getFieldTypeEnum();
  },
  methods: {
    handleTableData(tableData) {
      tableData.forEach((item) => {
        if (!item.uuid) {
          item.uuid = uuidv4();
        }
        if (item.childList && item.childList.length > 0) {
          item.childList = this.handleTableData(item.childList);
        }
      });
      return tableData;
    },
    delId(treeList, uuid) {
      if (!treeList || !treeList.length) {
        return;
      }
      for (let i = 0; i < treeList.length; i++) {
        if (treeList[i].uuid === uuid) {
          treeList.splice(i, 1);
          break;
        }
        this.delId(treeList[i].children, uuid);
      }
    },
    findId(tableData, uuid, callback) {
      tableData.forEach((item) => {
        if (item.uuid === uuid) {
          callback(item);
        } else if (item.childList && item.childList.length > 0) {
          this.findId(item.childList, uuid, callback);
        }
      });
    },
    async handleSave() {
      let categoryName = this.categoryEnumList.find(
        (item) => item.code === this.form.categoryCode
      ).name;
      let res = await request({
        url: "/user/apiDoc/edit",
        method: "post",
        data: {
          ...this.form,
          requestList: this.requestList,
          responseList: this.responseList,
          responseExample: this.responseExample,
          requestExample: this.requestExample,
          id: this.form.id,
          categoryName: categoryName,
        },
      });
      if (res.code === 200) {
        this.$message({
          message: "操作成功",
          type: "success",
        });
        this.$router.go(0);
      }
    },
    fieldTypeChange(val) {},
    async getInfo() {
      let queryParams = this.$route.query;
      let res = await request({
        url: `/user/apiDoc/${queryParams.id}`,
        methods: "get",
      });
      if (res.code === 200) {
        let responseData = res.data;
        this.requestList = this.handleTableData(responseData.requestList);
        this.responseList = this.handleTableData(responseData.responseList);
        this.form = {
          id: queryParams.id,
          categoryCode: responseData.categoryCode,
          categoryName: responseData.categoryName,
          apiMethod: responseData.apiMethod,
          apiName: responseData.apiName,
          remark: responseData.remark,
        };
        this.responseExample = responseData.responseExample;
        this.requestExample = responseData.requestExample;
      }
    },
    async getApiCategoryEnum() {
      let res = await request({
        url: "/common/enum/ApiCategoryEnum",
        methods: "get",
      });
      this.categoryEnumList = res;
    },
    async getFieldTypeEnum() {
      let res = await request({
        url: "/common/enum/FieldTypeEnum",
        methods: "get",
      });
      this.fieldTypeEnumList = res;
      res.forEach((item) => {
        this.fieldTypeMap[item.code] = item.name;
      });
    },
    requestFormAdd(item) {
      if (item && item.uuid) {
        this.requestForm.uuid = item.uuid;
      }
      this.requsetVisible = true;
    },
    requestFormDetail(item) {
      this.requestForm = {
        fieldName: "",
        fieldType: null,
        maxLength: null,
        required: null,
        exampleValue: "",
        remark: "",
      };
      this.requestForm = item;
      this.requsetVisible = true;
    },
    requestFormDel(row) {
      this.delId(this.requestList, row.uuid);
    },
    requestFormCancel() {
      this.requsetVisible = false;
    },
    responseFormAdd(item) {
      if (item && item.uuid) {
        this.responseForm.uuid = item.uuid;
      }
      this.responseForm = {
        fieldName: "",
        fieldType: null,
        maxLength: null,
        required: null,
        exampleValue: "",
        remark: "",
      };
      this.responseVisible = true;
    },
    responseFormDetail(item) {
      this.responseForm = item;
      this.responseVisible = true;
    },
    responseFormDel(row) {
      this.delId(this.responseList, row.uuid);
    },

    responseFormCancel() {
      this.responseVisible = false;
    },
    requestFormSubmit() {
      if (this.requestForm.uuid) {
        let that = this;
        const callback = (item) => {
          that.requestForm.uuidArr = item;
        };
        this.findId(this.requestList, this.requestForm.uuid, callback);

        let valueObj = deepClone(this.requestForm);
        delete valueObj.uuid;
        delete valueObj.uuidArr;
        if (this.requestForm.uuidArr.childList) {
          this.requestForm.uuidArr.childList.push(valueObj);
        } else {
          this.requestForm.uuidArr.childList = [valueObj];
        }
        this.requestList = deepClone(this.handleTableData(this.requestList));
      } else {
        this.requestList.push({
          ...this.requestForm,
        });
      }
      this.requsetVisible = false;
    },
    responseFormSubmit() {
      if (this.responseForm.uuid) {
        let that = this;
        const callback = (item) => {
          that.responseForm.uuidArr = item;
        };
        this.findId(this.responseList, this.responseForm.uuid, callback);
        let valueObj = deepClone(this.responseForm);
        delete valueObj.uuid;
        delete valueObj.uuidArr;
        if (this.responseForm.uuidArr.childList) {
          this.responseForm.uuidArr.childList.push(valueObj);
        } else {
          this.responseForm.uuidArr.childList = [valueObj];
        }
        this.responseList = deepClone(this.handleTableData(this.responseList));
      } else {
        this.responseList.push({
          ...this.responseForm,
        });
      }

      console.log("responseList", this.responseList);
      this.responseVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.page {
  padding: 50px;
  .table-top {
    margin: 10px;
    display: flex;
    justify-content: space-between;
  }
  .form-wrap {
    width: 800px;
  }
  .footer {
    margin: 30px;
  }
}
</style>
